package project.service;


import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Service
public class FileServiceImpl implements FileService {
    // 文件访问域名
    private static final String DOMAIN = "http://localhost:8088/file/download/";

    // 文件存储目录（改用更通用的路径格式）
    private static final String STORE_DIR = "E:/javacode/Optioner/src/main/resources/pict";

    @Override
    public String uploadFile(MultipartFile file, String fileName) throws IOException {
        // 创建目标文件路径
        Path destPath = Paths.get(STORE_DIR, fileName);

        // 确保目录存在
        Files.createDirectories(destPath.getParent());

        // 使用transferTo方法保存文件（Spring方式）
        file.transferTo(destPath);

        // 返回图片url
        String url = DOMAIN + fileName;
        System.out.println("文件url: " + url);
        return url;
    }

    @Override
    public void downloadFile(String fileName, HttpServletRequest request, HttpServletResponse response) {
        try {
            Path filePath = Paths.get(STORE_DIR, fileName);

            // 验证文件存在
            if (!Files.exists(filePath)) {
                response.setStatus(404);
                return;
            }

            // 设置响应头
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
                    "attachment; filename=\"" + filePath.getFileName() + "\"");

            // 使用NIO方式传输文件
            Files.copy(filePath, response.getOutputStream());
            response.flushBuffer();
        } catch (IOException e) {
            response.setStatus(404);
        }
    }

    @Override
    public boolean deleteFile(String fileName) {
        try {
            return Files.deleteIfExists(Paths.get(STORE_DIR, fileName));
        } catch (IOException e) {
            return false;
        }
    }
}